package com.example.websocket.another.component;

import com.example.websocket.another.config.ThreadPoolTaskConfig;
import com.example.websocket.another.constant.RedisKeyPrefix;
import com.example.websocket.another.dto.NotifyBean;
import com.example.websocket.another.entity.UserEntity;
import com.example.websocket.another.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @author lr
 */
@Component
@Slf4j
public class WebSocketSendAsync {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户连接或者用户断开时，发送当前所有在线用户信息通知给用户客户端
     */
    @Async(ThreadPoolTaskConfig.TASK_EXECUTOR_NAME)
    public void sendToAllUsers() {
        LinkedList<Long> list = getAllUserOnline();
        if (list != null && list.size() > 0) {
            // 根据用户id 查询
            List<UserEntity> userEntities = userMapper.getAllByUserIds(list);
            NotifyBean notifyBean = NotifyBean.builder().content("服务器 Send all persons id！").data(userEntities).build();
            //发送所有人
            simpMessagingTemplate.convertAndSend("/topic/public", notifyBean);
        }
    }

    public LinkedList<Long> getAllUserOnline() {
        Set<String> keys = stringRedisTemplate.keys(RedisKeyPrefix.WEBSOCKET_REDIS_KEY + "*");
        if (keys == null || keys.size() < 1) {
            log.info("当前没有用户！");
            return null;
        } else {
            LinkedList<Long> list = new LinkedList<>();
            for (String key : keys) {
                list.add(Long.valueOf(key.replace(RedisKeyPrefix.WEBSOCKET_REDIS_KEY, "")));
            }
            return list;
        }

    }

}
